package com.qs.springboot.amqp.direct;

import com.qs.springboot.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费端：绑定队列direct_exchange_queue_test2，同时绑定routingKey分别为update、delete、insert
 */
public class Recv2 {

    private final static String queue_name = "direct_exchange_queue_test2";
    private final static String exchange_name = "direct_exchange_test";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(queue_name, false, false, false, null);

        //绑定队列到交换机，同时指定需要订阅的routingKey（也就是说当交换机转发信息包含绑定的routingKey，才会被这个消费者消费）
        channel.queueBind(queue_name, exchange_name, "update");
        channel.queueBind(queue_name, exchange_name, "delete");
        channel.queueBind(queue_name, exchange_name, "insert");

        DefaultConsumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body);
                System.out.println("[消费者2] received：" + message);
            }
        };

        //监听队列，自动ack
        channel.basicConsume(queue_name, true, consumer);
    }
}
